#include <iostream>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>


using namespace std;

void Usage(const std::string &proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

// ./tcpclient serverip serverport

int main(int argc, char *argv[])
{
    if (argc != 3) 
    {
        Usage(argv[0]);
        exit(1);
    }

    string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET, serverip.c_str(), &(server.sin_addr));

    while (true)
    {
        int cnt = 5;     //重连次数
        int isreconnect = false;
        int sockfd = 0;
        sockfd = socket(AF_INET, SOCK_STREAM, 0);

        if (sockfd < 0)
        {
            std::cerr << "socket error" << std::endl;
            return 1;
        }

        //设置重连机制
        do      
        {
            // tcp客户端要不要bind？1 要不要显示的bind？0 系统进行bind，随机端口
            // 客户端发起connect的时候，进行自动随机bind
            int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                isreconnect = true;     //设置重连标志
                cnt--;
                std::cerr << "connect error..., reconnect: " << cnt << std::endl;
                sleep(2);
            }
            else
                break;
        }while (cnt && isreconnect);     //重连次数为0，退出循环

        if (cnt == 0)
        {
            std::cerr << "user offline..." << std::endl;
            break;
        }

        string msg;
        std::cout << "Please Enter# ";
        std::getline(std::cin, msg);

        // TCP在接受发送数据的时候使用的接口有send、write、read、recv
        int n = write(sockfd, msg.c_str(), msg.size());
        if (n < 0)
        {
            std::cerr << "write error..." << std::endl;
            // break;
        }

        char inbuf[1024] = {0};
        n = read(sockfd, inbuf, sizeof(inbuf));
        if (n > 0)
        {
            inbuf[n] = 0;
            std::cout << inbuf << std::endl;
        }
        else{       
            // break;   不选择退出，而是断线重连
        }
        close(sockfd);   //每次循环都会新建一个套接字描述符，所以需要关闭套接字描述符
    }

    return 0;
}